{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">{if condition="isset($detail.id)"}编辑法院{else /}新增法院{/if}</div>
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="webform">
                {if condition="isset($detail.id)"}<input type="hidden" name="id" value="{$detail.id}">{/if}
                <div class="layui-form-item">
                    <label class="layui-form-label">法院名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" required lay-verify="required" placeholder="请输入法院名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">法院级别</label>
                    <div class="layui-input-block">
                        <select name="level" required lay-verify="required">
                            <option value="">请选择级别</option>
                            <option value="1">最高人民法院</option>
                            <option value="2">高级人民法院</option>
                            <option value="3">中级人民法院</option>
                            <option value="4">基层人民法院</option>
                            <option value="5">法庭</option>
                            <option value="6">执行局</option>
                            <option value="7">其他</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">所在地区</label>
                    <div class="layui-input-inline">
                        <select name="provinceid" lay-filter="provinceid">
                            <option value="">请选择省份</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="cityid" lay-filter="cityid">
                            <option value="">请选择城市</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="distid" lay-filter="distid">
                            <option value="">请选择区/县</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">详细地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" placeholder="请输入详细地址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="webform">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const moduleInit = ['tool']; // 确保 tool 模块已加载

    function gouguInit() {
        // 编辑模式下预加载数据
        {if condition="isset($detail.id)"}
        var formData = {
            id: {$detail.id},
            name: '{$detail.name}',
            level: '{$detail.level}',
            provinceid: '{$detail.provinceid}',
            cityid: '{$detail.cityid}',
            distid: '{$detail.distid}',
            address: '{$detail.address}'
        };
        {/if}
        layui.use(['form', 'oaPicker'], function () {
            var form = layui.form, oaPicker = layui.oaPicker, tool = layui.tool;

            // 定义 loadRegionOptions 函数
            function loadRegionOptions(selectName, url, params = {}) {
                return new Promise((resolve) => {
                    let $select = $(`select[name="${selectName}"]`);
                    $select.html('<option value="">加载中...</option>');
                    form.render('select');

                    $.get(url, params)
                       .done(function(data) {
                            if (data && data.data && Array.isArray(data.data)) {
                                var redata = data.data;
                                var html = '<option value="">请选择</option>';
                                for (var i = 0; i < redata.length; i++) {
                                    var selected = params.selectedId && redata[i].id == params.selectedId ? 'selected' : '';
                                    html += `<option value="${redata[i].id}" ${selected}>${redata[i].name}</option>`;
                                }
                                $select.html(html);
                            } else {
                                $select.html('<option value="">加载失败</option>');
                                layer.msg('加载地区数据失败');
                            }
                            form.render('select');
                            resolve();
                        })
                       .fail(function(jqXHR, textStatus, errorThrown) {
                            $select.html('<option value="">加载失败</option>');
                            layer.msg(`加载地区选项失败: ${textStatus}`);
                            form.render('select');
                            resolve();
                        });
                });
            }

            // 加载省份数据
            loadRegionOptions('provinceid', '/home/api/regionProvinces'{if condition="isset($detail.id)"}, {selectedId: formData.provinceid}{/if});
            
            // 编辑模式下预加载表单数据
            {if condition="isset($detail.id)"}
            form.val('webform', formData);
            
            // 重构省市区联动加载逻辑
            new Promise((resolve) => {
                if(formData.provinceid) {
                    loadRegionOptions('provinceid', '/home/api/regionProvinces', {selectedId: formData.provinceid})
                        .then(() => {
                            if(formData.cityid) {
                                return loadRegionOptions('cityid', '/home/api/regionCitys', {provinceId: formData.provinceid, selectedId: formData.cityid});
                            }
                        })
                        .then(() => {
                            if(formData.distid) {
                                return loadRegionOptions('distid', '/home/api/regionDists', {cityId: formData.cityid, selectedId: formData.distid});
                            }
                        })
                        .then(() => resolve());
                } else {
                    resolve();
                }
            });
            {/if}

            // 监听省份选择变化
            form.on('select(provinceid)', function (data) {
                loadRegionOptions('cityid', '/home/api/regionCitys', {provinceId: data.value})
                    .then(() => {
                        $('select[name="distid"]').html('<option value="">请选择区/县</option>');
                        form.render('select');
                    });
            });

            // 监听城市选择变化
            form.on('select(cityid)', function (data) {
                loadRegionOptions('distid', '/home/api/regionDists', {cityId: data.value});
            });

            // 监听表单提交
            form.on('submit(webform)', function(data){
                tool.post(data.form.action, data.field, function(res){
                    if(res.code === 0) {
                        layer.msg(res.msg, {icon: 1});
                        setTimeout(function(){
                            parent.layui.table.reload('courtTable'); // 修改为正确的表格ID
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index); // 关闭弹层
                        }, 1000);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                });
                return false;
            });
        });
    }
</script>
{/block}
<!-- /主体 -->
